package Jcat.cduestcbbs.tools;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcTemplate extends Template {
	PreparedStatement pstm = null;

	public Object execute(SqlExecutor sql) {
		try {
			String sqlS = sql.getSql();
			if (getSqlType(sqlS).equals("select")) {
				{
					if (this.getStatementType()) {
						return (this.getStatement()).executeQuery(sqlS);
					} else {

						return (this.pstm).executeQuery();

					}
				}
			} else {

				if (this.getStatementType()) {
					return (this.getStatement()).executeUpdate(sqlS) == 1 ? true
							: false;
				} else {

					return (this.pstm).executeUpdate() == 1 ? true : false;

				}

			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {

			this.close();
		}
		return null;
	}

	public String getSqlType(String sql) {
		String sqlS[] = sql.split(" ");
		for (int i = 0; i < sqlS.length; i++) {

			if (sqlS[i].equals("select")) {
				return "select";
			}
		}
		return "other";
	}

	public PreparedStatement getPreparedStatement() throws SQLException {
		return this.pstm;
	}

	public Statement getStatement() throws SQLException {
		return this.getConnection().createStatement();
	}

	public void setPreparedStatement(String sql, Object... args) {
		try {
			pstm = this.getConnection().prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < args.length; i++) {
			try {
				pstm.setObject(i + 1, args[i]);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

	public boolean getStatementType() {
		if (this.pstm == null) {
			return true;

		} else
			return false;

	}

	public static void main(String args[]) {

		final JdbcTemplate template = new JdbcTemplate();
		ResultSet rs = (ResultSet) template.execute(new SqlExecutor() {
			public String getSql() {
				String sql = "select * from person where person_name=?";
				template.setPreparedStatement(sql, "jason");
				return sql;
			}

		});
		try {
			while (rs.next()) {

				System.out.println(rs.getObject(1));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
